﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

using Newtonsoft.Json;

namespace Happy.Web.Mvc.Newtonsoft
{
    /// <summary>
    /// 使用Newtonsoft进行格式化。
    /// </summary>
    public sealed class NewtonsoftJsonResult : ActionResult
    {
        /// <summary>
        /// 内容编码。
        /// </summary>
        public Encoding ContentEncoding { get; set; }

        /// <summary>
        /// 内容类型。
        /// </summary>
        public string ContentType { get; set; }

        /// <summary>
        /// 将被序列化的对象。
        /// </summary>
        public object Data { get; set; }

        /// <inheritdoc />
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            HttpResponseBase response = context.HttpContext.Response;

            if (!string.IsNullOrEmpty(this.ContentType))
            {
                response.ContentType = this.ContentType;
            }
            else
            {
                response.ContentType = "application/json";
            }

            if (ContentEncoding != null)
            {
                response.ContentEncoding = this.ContentEncoding;
            }

            if (Data != null)
            {
                response.Write(JsonConvert.SerializeObject(this.Data));
            }
        }
    }
}
